package com.yuni.index.Controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yuni.index.Model.User;
import com.yuni.index.Repository.UserRepository;
import com.yuni.index.utils.RedisUtil;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/register")
public class RegisterController {

    private static final Logger logger = LoggerFactory.getLogger(RegisterController.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping
    public ResponseEntity<Map<String, Object>> registerUser(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String email = request.get("email");
            String code = request.get("code");

            // 验证验证码
            String savedCode = redisUtil.getCode(email);
            if (savedCode == null || !savedCode.equals(code)) {
                response.put("success", false);
                response.put("message", "验证码无效或已过期");
                return ResponseEntity.ok(response);
            }

            // 验证通过后注册用户
            User user = new User();
            user.setUserName(request.get("userName"));
            user.setEmail(email);
            user.setPassword(request.get("password"));

            boolean isRegistered = userRepository.saveUser(user);

            if (isRegistered) {
                response.put("success", true);
                response.put("message", "用户注册成功");
                return new ResponseEntity<>(response, HttpStatus.CREATED);
            } else {
                response.put("success", false);
                response.put("message", "注册失败，用户可能已存在");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            logger.error("Error occurred while registering user: ", e);
            response.put("success", false);
            response.put("message", "内部服务器错误");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
